package cn.org.eshow.util;

import cn.org.eshow.bean.JsApiTicket;
import cn.org.eshow.bean.Ticket;
import cn.org.eshow.bean.Token;
import cn.org.eshow.component.parser.http.Client;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信公众号带参数二维码工具类
 *
 * @author bill
 */
public class WeixinUtil {
    public static String WEIXIN_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    public static String WEIXIN_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create";
    public static String WEIXIN_QRCODE_URL = "https://mp.weixin.qq.com/cgi-bin/showqrcode";
    public static String TOKEN_GRANT_type = "client_credential";
    public static String WEIXIN_USER_INFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info";
    public static String WEIXIN_MENU_CREAT_URL = "https://api.weixin.qq.com/cgi-bin/menu/create";
    public static String WEIXIN_TEMP_SEND_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send";
    public static String WEIXIN_JS_API_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
    public static String WEIXIN_GROUPS_GET_URL = "https://api.weixin.qq.com/cgi-bin/groups/get";


    public final static String APP_Id = "wxbdbb6077713b6f2b";
    public final static String APP_SECRET = "6eac45acf04db7c0a15a65efba96b3af";
    public final static String APP_SHOP_ID = "1412473002";

    public final static String UPDATE_TEMP_ID = "7b9tDA1JwtnwSFFxO7CLdnogRxCPYlY0CS5gdv-r64I";
    public final static String REFUND_TEMP_ID = "ezmjNwv_sDv_u3M_P9FmPsNdLCvnKF4PzDAYXk6g0Fg";
    public final static String CANCEL_TEMP_ID = "jd9HZAiTWvgyFYrF6GcmS4d1wDITQJBxph0ky1zhes0";
    public final static String PAY_TEMP_ID = "vYtFZCxXmZjFXR7Z5ELA6MCefOXjda1ploEDak5F5Uw";

    /**
     * 获取access_token
     *
     * @return
     */
    public static String getToken(String appId, String appSecret) {
        String acce = "";
        Token token = null;
        try {
            //重新获取token
            StringBuilder sb = new StringBuilder();
            sb.append(WEIXIN_TOKEN_URL).append("?").append("grant_type=" + TOKEN_GRANT_type);
            sb.append("&appid=").append(appId.trim());
            sb.append("&secret=").append(appSecret.trim());


            String result = HtmlUtil.getContent(sb.toString(), "utf-8");

            ObjectMapper mapper = new ObjectMapper();
            token = mapper.readValue(result, Token.class);
            if (token.getAccess_token() != null) {
                acce = token.getAccess_token();
            }
            if (StringUtils.isEmpty(token.getErrcode())) {
                System.out.println(token.getErrcode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return acce;
    }

    /**
     * 获取access_token和expires_in
     *
     * @return
     */
    public static Token token(String appId, String appSecret) {
        String acce = "";
        Token token = null;
        try {
            //重新获取token
            StringBuilder sb = new StringBuilder();
            sb.append(WEIXIN_TOKEN_URL).append("?").append("grant_type=" + TOKEN_GRANT_type);
            sb.append("&appid=").append(appId.trim());
            sb.append("&secret=").append(appSecret.trim());


            String result = HtmlUtil.getContent(sb.toString(), "utf-8");

            ObjectMapper mapper = new ObjectMapper();
            token = mapper.readValue(result, Token.class);
            if (StringUtils.isEmpty(token.getErrcode())) {
                System.out.println(token.getErrcode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }


    /**
     * 根据token和scene_id获取ticket
     *
     * @param token
     * @param scene_id
     * @return
     */
    public static String getTicket(String token, BigInteger scene_id) {
        String tic = "";
        Ticket ticket = null;
        try {

            //重新请求获取ticket
            String url = WEIXIN_TICKET_URL.trim() + "?access_token=" + token.trim();
            String param = "{\"expire_seconds\": 1800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": " + scene_id + "}}}";

            String result = Client.post(url, param);
            ObjectMapper mapper = new ObjectMapper();
            ticket = mapper.readValue(result, Ticket.class);
            if (ticket.getTicket() != null) {
                tic = ticket.getTicket();
            }
            if (StringUtils.isEmpty(ticket.getErrcode())) {
                System.out.println(ticket.getErrcode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tic;
    }


    /**
     * 根据token和scene_id获取ticket
     *
     * @param token
     * @return
     */
    public static JsApiTicket jsApiTicket(String token) {
        String tic = "";
        JsApiTicket ticket = null;
        try {

            //重新请求获取ticket
            StringBuilder sb = new StringBuilder();
            sb.append(WEIXIN_JS_API_TICKET_URL).append("?");
            sb.append("&access_token=").append(token);
            sb.append("&type=").append("jsapi");

            String result = HtmlUtil.getContent(sb.toString(), "utf-8");

            ObjectMapper mapper = new ObjectMapper();
            ticket = mapper.readValue(result, JsApiTicket.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ticket;
    }

    /**
     * 根据ticket获取二维码地址
     *
     * @param ticket
     * @return
     */
    public static String getQrcode(String ticket) {
        try {
            ticket = URLEncoder.encode(ticket, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = WEIXIN_QRCODE_URL + "?ticket=" + ticket;
        return url;
    }

    public static String showQrcode(BigInteger scene_id) {

        String url = "";
        String token = getToken(APP_Id, APP_SECRET);
        if (token != null) {
            String ticket = getTicket(token, scene_id);
            if (ticket != null) {
                url = getQrcode(ticket);
            }
        }
        return url;
    }

    public static String showQrcode(String appId, String appSecret, BigInteger scene_id) {

        String url = "";
        String token = getToken(appId, appSecret);
        if (token != null) {
            String ticket = getTicket(token, scene_id);
            if (ticket != null) {
                url = getQrcode(ticket);
            }
        }
        return url;
    }

    public static String showQrcode(String token, BigInteger scene_id) {
        String url = "";
        if (token != null) {
            String ticket = getTicket(token, scene_id);
            if (ticket != null) {
                url = getQrcode(ticket);
            }
        }
        return url;
    }

    public static Map<String, String> userInfo(String openId) {
        Map<String, String> map = new HashMap<String, String>();

        String token = getToken(APP_Id, APP_SECRET);

        StringBuilder sb = new StringBuilder();
        sb.append(WEIXIN_USER_INFO_URL).append("?").append("access_token=" + token);
        sb.append("&openid=").append(openId.trim());
        sb.append("&lang=zh_CN");

        try {
            String result = HtmlUtil.getContent(sb.toString(), "utf-8");
            JSONObject object = JSON.parseObject(result);
            if (object != null) {
                if (object.containsKey("errcode")) {
                    System.out.println(object.getString("errcode"));
                    map.put("status", "0");
                } else {
                    map.put("status", "1");
                    map.put("nickname", object.getString("nickname"));
                    map.put("photo", object.getString("headimgurl"));
                }
            }
        } catch (Exception e) {
            map.put("status", "0");
            e.printStackTrace();
        }


        return map;
    }

    /**
     * 发送模板信息
     *
     * @return
     */
    public static void sendTemp(String openId, String tempId, String url, Map data) {
        String surl = "https://open.weixin.qq.com/connect/oauth2/authorize";
        surl += "?appid=" + APP_Id + "&redirect_uri=" + URLEncoder.encode(url);
        surl += "&response_type=code&scope=snsapi_base&state=index#wechat_redirect&connect_redirect=1";


        Map map = new HashMap();
        map.put("touser", openId);
        map.put("template_id", tempId);
        map.put("url", surl);
        map.put("data", data);
        String token = getToken(APP_Id, APP_SECRET);
        try {
            String result = Client.post(WEIXIN_TEMP_SEND_URL + "?access_token=" + token, JacksonUtil.toJson(map));
            if (!result.contains("ok")) {
                System.out.println(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //获取分组，判断当前token是否可用
    public static Boolean groups(String token) {
        StringBuilder sb = new StringBuilder();
        sb.append(WEIXIN_GROUPS_GET_URL).append("?").append("access_token=" + token);
        String result = null;
        try {
            result = HtmlUtil.getContent(sb.toString(), "utf-8");

            JSONObject object = JSON.parseObject(result);
            if (object != null) {
                if (object.containsKey("errcode")) {
                    System.out.println(object.getString("errcode"));
                    System.out.println(result);
                } else {
                    return Boolean.TRUE;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Boolean.FALSE;
    }


    public static void main(String[] args) {
//        System.out.println(showQrcode(BigInteger.valueOf(125)));
//        Map data = new HashMap();
//        Map first = new HashMap();
//        first.put("value", "您好，您的订单已接单");
//
//        Map keyword1 = new HashMap();
//        keyword1.put("value", "201612345678");
//
//        Map keyword2 = new HashMap();
//        keyword2.put("value", "2016-11-26 12：00：00");
//
//        Map keyword3 = new HashMap();
//        keyword2.put("value", "李师傅已接单");
//
//        Map remark = new HashMap();
//        remark.put("value", "请尽快查看详情");
//
//        data.put("first", first);
//        data.put("keyword1", keyword1);
//        data.put("keyword2", keyword2);
//        data.put("keyword3", keyword3);
//        data.put("remark", remark);
//        sendTemp("oJRFmwvkD-YNyr877IM3r-2lPhhY",UPDATE_TEMP_ID,"http://hpjiang.daoqun.com/center/order/",data);
        String s = "无锡市";
        if (s.charAt(2) == '市') {
            System.out.print(12);
            System.out.print(s.substring(0, 2));
        } else {
            System.out.print(s);
        }

    }

}
